package com.zhangmeng.tools.controller;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.sql.visitor.functions.If;
import com.zhangmeng.tools.utils.AlertUtils;
import com.zhangmeng.tools.utils.FxmlUtils;
import javafx.application.Platform;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.MapValueFactory;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : 芊芊墨客
 * @version : 1.0
 * @date : 2023-05-18 09:57
 */
@Slf4j
public class SqlQueryController {

    @FXML
    public TextField username;

    @FXML
    public TextField password;

    @FXML
    public Button query;

    @FXML
    public TextField ip;

    @FXML
    public TextField port;

    @FXML
    public TextField database;

    @FXML
    public TextArea query_area;

    @FXML
    public TableView<Map<String, SimpleStringProperty>> result_view;

    private JdbcTemplate jdbcTemplate;

    private final ObservableList<Map<String, SimpleStringProperty>> result_list = FXCollections.observableArrayList();

    private SimpleBooleanProperty is_exchange = new SimpleBooleanProperty(false);

    @FXML
    public void initialize() {

        result_view.setItems(result_list);

        ip.setText("127.0.0.1");
        port.setText("3306");
        database.setText("mystyle-blog");
        username.setText("root");
        password.setText("root");

        //绑定截图快捷键，使用快捷键达到点击按钮的目的
        KeyCombination keyCombination = KeyCombination.valueOf("ctrl+q");

        // 处理快捷键事件
        Runnable action = this::run_query;

        query.setOnKeyPressed(event -> {
            if (keyCombination.match(event)) {
                action.run();
                event.consume();
            }
        });

        query.setOnAction(event -> run_query());

        database.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                is_exchange.set(true);
            }
        });
    }

    public void run_query() {
        if (query_area.getSelectedText().length() == 0) {
            AlertUtils.alert_warning("请选择要执行的sql!");
            return;
        }

        String sql = query_area.getSelectedText();

        if (is_exchange.get()) {
            connection();
        }

        if (jdbcTemplate == null) {
            connection();
        }
        result_list.clear();
        result_view.getColumns().clear();

        new Thread(() -> {
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            Platform.runLater(() -> {
                if (list.size() > 0) {
                    Map<String, Object> map1 = list.get(0);
                    for (Map.Entry<String, Object> entry : map1.entrySet()) {
                        String key = entry.getKey();

                        if (key.equals("unique_identification_key")) {
                            continue;
                        }

                        if (key.equals("now_pos")) {//now_pos -> null
                            continue;
                        }

                        TableColumn<Map<String, SimpleStringProperty>, String> column = new TableColumn<>(key);
                        column.setCellValueFactory(new MapValueFactory(key));
                        result_view.getColumns().add(column);
                    }

                    for (Map<String, Object> map : list) {//unique_identification_key -> 07f83e41-6f0b-4801-b4c7-77778b3a6e50-1422840095098011648
                        Map<String, SimpleStringProperty> map2 = new HashMap<>();
                        for (Map.Entry<String, Object> entry : map.entrySet()) {
                            String key = entry.getKey();
                            String value = entry.getValue() == null ? "" : entry.getValue().toString();
                            map2.put(key, new SimpleStringProperty(value));
                        }
                        result_list.add(map2);
                    }
                }
            });
        }).start();
    }


    public void getJdbcTemplate() {
        jdbcTemplate = new JdbcTemplate();
        DruidDataSource datasource = new DruidDataSource();
        String url = "jdbc:mysql://" + ip.getText() + ":" + port.getText() + "/" + database.getText() + "?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true";
        String driverClassName = "com.mysql.jdbc.Driver";
        datasource.setUrl(url);
        datasource.setUsername(username.getText());
        datasource.setPassword(password.getText());
        datasource.setDriverClassName(driverClassName);
        jdbcTemplate.setDataSource(datasource);
    }

    public void connection() {

        if (ip.getText().length() == 0) {
            AlertUtils.alert_warning("ip不能为空!");
            return;
        }

        if (port.getText().length() == 0) {
            AlertUtils.alert_warning("端口不能为空!");
            return;
        }

        if (database.getText().length() == 0) {
            AlertUtils.alert_warning("数据库名不能为空!");
            return;
        }

        getJdbcTemplate();
        is_exchange.set(false);
    }

}
